package com.ruoyi.bole.integral.service.impl;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.ruoyi.bole.integral.domain.BoleIntegralApplication;
import com.ruoyi.bole.integral.mapper.BoleIntegralApplicationMapper;
import com.ruoyi.bole.integral.service.IBoleIntegralApplicationService;
import com.ruoyi.bole.integral.vo.IntegrationRankVO;
import com.ruoyi.bole.wechatSubscribe.domain.BoleWechatSubscribeUser;
import com.ruoyi.bole.wechatSubscribe.service.IBoleWechatSubscribeUserService;
import com.ruoyi.bole.wechatSubscribe.service.WxSubscribeService;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


/**
 * 积分申请Service业务层处理
 *
 * @author ruoyi
 * @date 2025-03-23
 */
@Service
public class BoleIntegralApplicationServiceImpl implements IBoleIntegralApplicationService {
    @Autowired
    private BoleIntegralApplicationMapper boleIntegralApplicationMapper;

    @Override
    public List<BoleIntegralApplication> selectBoleIntegralApplicationByIds(List<Long> ids) {
        return boleIntegralApplicationMapper.selectBoleIntegralApplicationByIds(ids);
    }

    //排行榜
    @Override
    // BoleIntegralServiceImpl.java
    public List<IntegrationRankVO> getIntegrationRank(int offset, int pageSize, Integer seasonId) {
        List<IntegrationRankVO> list = boleIntegralApplicationMapper.selectIntegrationRank(offset, pageSize, seasonId);
        System.out.println(list);
        // 计算排名
//        int rank = 1;
//        for (int i = 0; i < list.size(); i++) {
//            if (i > 0 && !list.get(i).getTotalScore().equals(list.get(i-1).getTotalScore())) {
//                rank = i + 1;
//            }
//            list.get(i).setRank(rank);
//        }

        return list;
    }

    /**
     * 查询积分申请
     *
     * @param id 积分申请主键
     * @return 积分申请
     */
    @Override
    public BoleIntegralApplication selectBoleIntegralApplicationById(Long id) {
        return boleIntegralApplicationMapper.selectBoleIntegralApplicationById(id);
    }

    /**
     * 查询积分申请列表
     *
     * @param boleIntegralApplication 积分申请
     * @return 积分申请
     */
    @Override
    public List<BoleIntegralApplication> selectBoleIntegralApplicationList(BoleIntegralApplication boleIntegralApplication) {
        return boleIntegralApplicationMapper.selectBoleIntegralApplicationList(boleIntegralApplication);
    }

    /**
     * 新增积分申请
     *
     * @param boleIntegralApplication 积分申请
     * @return 结果
     */
    @Override
    public int insertBoleIntegralApplication(BoleIntegralApplication boleIntegralApplication) {
        boleIntegralApplication.setCreateTime(DateUtils.getNowDate());
        return boleIntegralApplicationMapper.insertBoleIntegralApplication(boleIntegralApplication);
    }

    /**
     * 修改积分申请
     *
     * @param boleIntegralApplication 积分申请
     * @return 结果
     */
    @Autowired
    private ISysUserService service;
    @Autowired
    private IBoleWechatSubscribeUserService boleWechatSubscribeUserService;
    @Autowired
    private WxSubscribeService wxSubscribeService;
    private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(BoleIntegralApplicationServiceImpl.class);

    @Override
    public int updateBoleIntegralApplication(BoleIntegralApplication boleIntegralApplication) {
        //通过util获取用户id

        if (boleIntegralApplication.getIsApplication() != null) {
            System.out.println("审核按钮");
            if (boleIntegralApplication.getStatus().equals("1")) {
                System.out.println("审核通过");
                service.addScore(boleIntegralApplication.getUserId(), Math.toIntExact(boleIntegralApplication.getScore()));
                //发送通过消息
                BoleWechatSubscribeUser boleWechatSubscribeUser = boleWechatSubscribeUserService.selectBoleWechatSubscribeUserByUserId(boleIntegralApplication.getUserId());
                //为空不发送
                if (boleWechatSubscribeUser != null) {
                    // 外层Map存储所有字段
                    Map<String, String> data = new HashMap<>();
                    // 每个字段需要包装成{"value": "实际值"}的格式
                    try {
                        SysUser sysUser = service.selectUserById(boleIntegralApplication.getUserId());
                        data.put("number1", boleIntegralApplication.getScore().toString());
                        data.put("number2", String.valueOf((sysUser.getScore() + boleIntegralApplication.getScore())));
                        data.put("time3", LocalDateTime.now()
                                .format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                        data.put("thing4", "积分审核通过：由" + SecurityUtils.getLoginUser().getUser().getNickName() + "审核");
                        wxSubscribeService.sendSubscribeMessage(boleWechatSubscribeUser.getOpenid(),
                                boleWechatSubscribeUser.getTemplateId(), data);
                        boleWechatSubscribeUser.setPushCount(boleWechatSubscribeUser.getPushCount() + 1);
                        boleWechatSubscribeUser.setLastPushTime(new Date());
                        boleWechatSubscribeUser.setSubscribeStatus(2L);
                        boleWechatSubscribeUserService.updateBoleWechatSubscribeUser(boleWechatSubscribeUser);
                    } catch (Exception e) {
                        // 记录日志
                        boleWechatSubscribeUser.setRemark(e.getMessage());
                        boleWechatSubscribeUserService.updateBoleWechatSubscribeUser(boleWechatSubscribeUser);
                        log.error("发送订阅消息失败", e);
                    }

                }
            } else if (boleIntegralApplication.getStatus().equals("2")) {
                //发送不通过消息
                BoleWechatSubscribeUser boleWechatSubscribeUser = boleWechatSubscribeUserService.selectBoleWechatSubscribeUserByUserId(boleIntegralApplication.getUserId());
                //为空不发送
                if (boleWechatSubscribeUser != null) {
                    // 外层Map存储所有字段
                    Map<String, String> data = new HashMap<>();
                    // 每个字段需要包装成{"value": "实际值"}的格式
                    try {
                        SysUser sysUser = service.selectUserById(boleIntegralApplication.getUserId());
                        data.put("number1", "0");
                        data.put("number2", String.valueOf((sysUser.getScore())));
                        data.put("time3", LocalDateTime.now()
                                .format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                        data.put("thing4", "积分审核不通过：由" + SecurityUtils.getLoginUser().getUser().getNickName() + "审核");
                        wxSubscribeService.sendSubscribeMessage(boleWechatSubscribeUser.getOpenid(),
                                boleWechatSubscribeUser.getTemplateId(), data);
                        //删除用户的订阅信息
                        boleWechatSubscribeUser.setPushCount(boleWechatSubscribeUser.getPushCount() + 1);
                        boleWechatSubscribeUser.setLastPushTime(new Date());
                        boleWechatSubscribeUser.setSubscribeStatus(2L);
                        boleWechatSubscribeUserService.updateBoleWechatSubscribeUser(boleWechatSubscribeUser);
                    } catch (Exception e) {
                        // 记录日志
                        boleWechatSubscribeUser.setRemark(e.getMessage());
                        boleWechatSubscribeUserService.updateBoleWechatSubscribeUser(boleWechatSubscribeUser);
                        log.error("发送订阅消息失败", e);
                    }
                }
            }
        }
        boleIntegralApplication.setUpdateTime(DateUtils.getNowDate());
        return boleIntegralApplicationMapper.updateBoleIntegralApplication(boleIntegralApplication);


    }

    /**
     * 批量删除积分申请
     *
     * @param ids 需要删除的积分申请主键
     * @return 结果
     */
    @Override
    public int deleteBoleIntegralApplicationByIds(Long[] ids) {
        return boleIntegralApplicationMapper.deleteBoleIntegralApplicationByIds(ids);
    }

    /**
     * 删除积分申请信息
     *
     * @param id 积分申请主键
     * @return 结果
     */
    @Override
    public int deleteBoleIntegralApplicationById(Long id) {
        return boleIntegralApplicationMapper.deleteBoleIntegralApplicationById(id);
    }
}
